<template>
    <div id="Site">
        <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>接种管理</el-breadcrumb-item>
            <el-breadcrumb-item>接种地点管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 接种地点卡片区 -->
        <el-card class="box-card">
            <el-form :inline="true" ref="form" :model="queryMap" label-width="70px" size="small">
                <el-row :gutter="2">
                    <el-col :span="8">
                        <el-form-item label="接种点名称" label-width="100px">
                            <el-input
                                    @keyup.enter.native="searchSite"
                                    @clear="searchSite"
                                    clearable
                                    v-model="queryMap.vaccSiteName"
                                    placeholder="请输入接种点名称查询"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="电话号码">
                            <el-input
                                    @keyup.enter.native="searchSite"
                                    @clear="searchSite"
                                    clearable
                                    v-model="queryMap.phoneNumber"
                                    placeholder="请输入接种点电话号码查询"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="详细地址">
                            <el-input clearable @clear="searchSite" v-model="queryMap.address" placeholder="请输入详细地址查询"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="区域" label-width="100px">
                            <el-input clearable @clear="searchSite" v-model="queryMap.area" placeholder="请输入所属区域查询"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item>
                            <el-button  @click="reset" icon="el-icon-refresh">重置</el-button>
                            <el-button type="primary" @click="searchSite" icon="el-icon-search">查询</el-button>
                            <el-button
                                    type="success"
                                    icon="el-icon-plus"
                                    @click="addDialogVisible=true"
                                    v-hasPermission="'vaccineSite:add'"
                            >添加</el-button>
                            <!-- <el-button @click="downExcel" v-hasPermission="'site:export'"  icon="el-icon-download">导出</el-button> -->
                        </el-form-item>
                    </el-col>
                </el-row>       
            </el-form>

            <!-- 表格区域 -->
            <el-table v-loading="loading" size="small" :data="siteList" border style="width: 100%;" :header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }" height="430">
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column prop="vaccSiteName" label="接种点名称" width="180"></el-table-column>
                <el-table-column prop="area" label="所属区域" width="250" ></el-table-column>
                <el-table-column prop="phoneNumber" label="接种点电话" width="150"></el-table-column>
                <el-table-column prop="address" label="详细地址" width="200"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" ></el-table-column>
                <el-table-column label="操作" >
                    <template slot-scope="scope">
                        <el-button   v-hasPermission="'vaccineSite:edit'" size="medium" type="primary" icon="el-icon-edit-outline" @click="edit(scope.row.id)"></el-button>
                        <el-button v-hasPermission="'vaccineSite:delete'" type="danger" size="medium"  icon="el-icon-delete" @click="del(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
                    style="margin-top:10px;"
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryMap.pageNum"
                    :page-sizes="[7, 15, 20, 30]"
                    :page-size="queryMap.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>

            <!-- 添加对话框 -->
            <el-dialog title="添加接种地点信息" @close="closeDialog" :visible.sync="addDialogVisible" width="50%;">
            <!-- 表单 -->
            <span>
            <el-form
                    :model="addForm"
                    :label-position="labelPosition"
                    :rules="addFormRules"
                    ref="addFormRef"
                    label-width="95px"
            >
            <el-form-item label="接种点名称"  prop="vaccSiteName">
                <el-input v-model="addForm.vaccSiteName"></el-input>
            </el-form-item>
            <el-row :gutter="2">
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <el-form-item label="所属区域" prop="valueProvince">
                            <el-select
                                    v-model="addForm.valueProvince"
                                    placeholder="请选择省"
                                    @change="changeProvince"
                            >
                                <el-option
                                        v-for="item in provinceList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                    <el-form-item label="城市" label-width="60px"  prop="valueCity">
                        <el-select
                                v-model="addForm.valueCity"
                                placeholder="请选择市"
                                @change="changeCity"
                        >
                            <el-option
                                    v-for="item in cityOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="grid-content bg-purple">
                        <el-form-item label="区县" label-width="60px" prop="valueOrigin">
                            <el-select
                                    v-model="addForm.valueOrigin"
                                    placeholder="请选择区"
                                    @change="changeOrigin"
                            >
                                <el-option
                                        v-for="item in originOptions"
                                        :key="item.label"
                                        :label="item.label"
                                        :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                </el-col>
            </el-row>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="addForm.address"></el-input>
            </el-form-item>
            <el-form-item label="电话号码" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber"></el-input>
            </el-form-item>
          </el-form>
            </span>
                <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button
                            type="primary"
                            @click="addSite"
                            :loading="btnLoading"
                            :disabled="btnDisabled"
                >确 定</el-button>
            </span>
            </el-dialog>

            <!-- 修改对话框 -->
            <el-dialog title="修改接种地点信息" :visible.sync="editDialogVisible" width="50%" @close="editClose">
            <span>
                <el-form
                        :model="editForm"
                        :label-position="labelPosition"
                        :rules="addFormRules"
                        ref="editFormRef"
                        label-width="95px"
                >
                <el-form-item label="接种点名称"  prop="vaccSiteName">
                    <el-input disabled v-model="editForm.vaccSiteName"></el-input>
                </el-form-item>
                <el-form-item label="所属地区" prop="area">
                    <el-input disabled v-model="editForm.area"></el-input>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model="editForm.address"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="phoneNumber">
                    <el-input v-model="editForm.phoneNumber"></el-input>
                </el-form-item>
                </el-form>
                </span>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button
                                type="primary"
                                @click="updateSite"
                                :loading="btnLoading"
                                v-hasPermission="'vaccineSite:update'"
                                :disabled="btnDisabled"
                    >确 定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import axios from "axios";
    export default {
        data() {
            const checkPhone = (rule, value, callback) => {
                const phoneReg = /^1[34578]\d{9}$$/;
                if (!value) {
                    return callback(new Error("电话号码不能为空"));
                }
                setTimeout(() => {
                    if (!Number.isInteger(+value)) {
                        callback(new Error("请输入数字值"));
                    } else {
                        if (phoneReg.test(value)) {
                            callback();
                        } else {
                            callback(new Error("电话号码格式不正确"));
                        }
                    }
                }, 100);
            };
            return {
                btnLoading: false,
                btnDisabled: false,
                loading: true,
                total: 0,
                addDialogVisible: false, //添加对话框,
                editDialogVisible: false, //修改对话框
                assignDialogVisible: false, //分配角色对话框
                labelPosition: "right", //lable对齐方式
                provinceList: [], // 省列表
                cityList: [], // 市列表
                originList: [], // 区列表
                cityOptions: [], // 市下拉框数据
                originOptions: [], // 区下拉框数据
                //查询对象
                queryMap: {
                    pageNum: 1,
                    pageSize: 7,
                    vaccSiteName:"",
                    phoneNumber: "",
                    area: "",
                    address: ""
                },
                siteList: [],
                //添加表单
                addForm: {
                    valueProvince:"",
                    valueCity:"",
                    valueOrigin:"",
                    vaccSiteName:"",
                    phoneNumber: "",
                    address: ""
                }, 
                editForm: {}, //更新表单
                addFormRules: {
                    vaccSiteName: [
                        { required: true, message: "请输入接种地点姓名", trigger: "blur" },
                        { min: 2, max: 20, message: "长度在 2 到 20 个字符之间", trigger: "blur" }
                    ],
                    valueProvince: [
                        { required: true, message: "请输入省份", trigger: "blur" }
                    ],
                    valueCity: [{ required: true, message: "请输入城市", trigger: "blur" }],
                    valueOrigin: [
                        { required: true, message: "请输入区县", trigger: "blur" }
                    ],
                    address: [
                        { required: true, message: "请输入详细地址", trigger: "blur" },
                        { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
                    ],
                    phoneNumber: [
                        {
                            required: true,
                            message: "请输入联系方式",
                            validator: checkPhone,
                            trigger: "blur"
                        }
                    ]
                }, //添加表单验证规则
                roles: [], //角色
                value: [], //用户拥有的角色
                uid: ""
            };
        },
        methods: {
            /**
             * 重置
             */
            reset(){
                this.queryMap= {
                    pageNum: 1,
                    pageSize: 7,
                    vaccSiteName:"",
                    phoneNumber: "",
                    area: "",
                    address: ""
                };
            },
            /**
             * 获取json文件
             */
            _getJsonData() {
                this.$http.get("/json/provinces.json").then(res => {
                    this.provinceList = [];
                    this.cityList = [];
                    this.originList = [];
                    res.data.forEach(item => {
                        if (item.value.match(/0000$/)) {
                            this.provinceList.push({
                                value: item.value,
                                label: item.name,
                                children: []
                            });
                        } else if (item.value.match(/00$/)) {
                            this.cityList.push({
                                value: item.value,
                                label: item.name,
                                children: []
                            });
                        } else {
                            this.originList.push({
                                value: item.value,
                                label: item.name
                            });
                        }
                    });
                    for (let index in this.provinceList) {
                        for (let index1 in this.cityList) {
                            if (
                                this.provinceList[index].value.slice(0, 2) ===
                                this.cityList[index1].value.slice(0, 2)
                            ) {
                                this.provinceList[index].children.push(this.cityList[index1]);
                            }
                        }
                    }
                    for (let item1 in this.cityList) {
                        for (let item2 in this.originList) {
                            if (
                                this.originList[item2].value.slice(0, 4) ===
                                this.cityList[item1].value.slice(0, 4)
                            ) {
                                this.cityList[item1].children.push(this.originList[item2]);
                            }
                        }
                    }
                });
            },
            // 选择省
            changeProvince(val) {
                this.provinceList.forEach((province, index) => {
                    if (val.toString() === this.provinceList[index].value) {
                        this.cityOptions = this.provinceList[index].children;
                        this.addForm.valueCity = this.provinceList[
                            index
                            ].children[0].value; //设置市的值
                        this.addForm.city = this.provinceList[index].children[0].label;

                        this.addForm.valueOrigin = this.provinceList[
                            index
                            ].children[0].children[0].value; //设置县的值
                        this.addForm.origin = this.provinceList[
                            index
                            ].children[0].children[0].label;

                        this.originOptions = this.provinceList[index].children[0].children;
                        //set value
                        this.addForm.province = this.provinceList[index].label;
                    }
                });
            },
            // 选择市
            changeCity(val) {
                this.cityList.forEach((city, index) => {
                    if (val.toString() === this.cityList[index].value) {
                        this.originOptions = this.cityList[index].children;
                        this.addForm.valueOrigin = this.cityList[index].children[0].value; //设置县的值;
                        //set value
                        this.addForm.city = this.cityList[index].label;
                    }
                });
            },
            // 选择区
            changeOrigin(val) {
                this.addForm.valueOrigin = val;

                this.originList.forEach((origin, index) => {
                    if (val.toString() === this.originList[index].value) {
                        //set value
                        this.addForm.origin = this.originList[index].label;
                    }
                });
                //添加this.$forceUpdate();进行强制渲染，效果实现。搜索资料得出结果：因为数据层次太多，render函数没有自动更新，需手动强制刷新。
                this.$forceUpdate();
            },
            /**
             * 添加接种地点
             */
            async addSite() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    } else {
                        this.addForm.area =
                            this.addForm.province +
                            "-" +
                            this.addForm.city +
                            "-" +
                            this.addForm.origin;
                        this.btnLoading = true;
                        this.btnDisabled = true;
                        const { data: res } = await this.$http.post("vaccine/site/add", this.addForm);
                        if(res.success){
                            this.$notify.success({
                                title:'操作成功',
                                message:'接种地点添加成功!',
                            });
                            this.addForm = {};
                            await this.getSitesList();
                        } else {
                            return this.$message.error(res.message);
                        }
                        this.addDialogVisible = false;
                        this.btnLoading = false;
                        this.btnDisabled = false;
                    }
                });
            },
            /**
             * 加载接种地点列表
             */
            async getSitesList(){
                const { data: res } = await this.$http.get("vaccine/site/findSiteList", {
                    params: this.queryMap
                });
                if(!res.success){
                    return this.$message.error(res.message);
                }
                this.total = res.data.total;
                this.siteList = res.data.siteList;
            },
            /**
             * 修改接种地点信息
             */
            async edit(id) {
                const { data: res } = await this.$http.get("vaccine/site/edit/" + id);
                if(res.success){
                    this.editForm = res.data.site;
                    this.editDialogVisible = true;
                } else {
                    return this.$message.error(res.message);
                }
            },
            /**
             * 更新接种点
             */
            async updateSite() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) {
                        return;
                    } else {
                        this.btnLoading = true;
                        this.btnDisabled = true;
                        const { data: res } = await this.$http.put(
                            "vaccine/site/update/" ,this.editForm
                        );
                        if(res.success){
                            this.$notify({
                                title: "操作成功",
                                message: "接种点基本信息已更新",
                                type: "success"
                            });
                            this.editForm = {};
                            await this.getSitesList();
                        } else {
                            this.$message.error(res.message);
                        }
                        this.editDialogVisible = false;
                        this.btnLoading = false;
                        this.btnDisabled = false;
                    }
                });
            },
            /**
             * 删除接种点信息
             */
            async del(id) {
                const res = await this.$confirm(
                    "此操作将永久删除该接种点, 是否继续?",
                    "提示",
                    {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning"
                    }
                ).catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除!"
                    });
                });
                if (res === "confirm") {
                    const { data: res } = await this.$http.delete("vaccine/site/delete/" + id);
                    if(res.success){
                        this.$notify.success({
                            title:'操作成功',
                            message:'接种点信息删除成功!',
                        });
                        this.getSitesList();
                    }else {
                        this.$message.error(res.message);
                    }
                }
            },
            /**
             * 搜索接种地点
             */
            searchSite() {
                this.queryMap.pageNum = 1;
                this.getSitesList();
            },
            /**
             *  改变页码
             */
            handleSizeChange(newSize) {
                this.queryMap.pageSize = newSize;
                this.getUserList();
            },
            /**
             * 翻页
             */
            handleCurrentChange(current) {
                this.queryMap.pageNum = current;
                this.getUserList();
            },
            /**
             * 关闭添加弹出框
             */
            closeDialog() {
                this.$refs.addFormRef.clearValidate();
                this.addForm = {};
            },
            /**
             * 关闭编辑弹出框
             */
            editClose() {
                this.$refs.editFormRef.clearValidate();
                this.editForm = {};
            }
        },
        created() {
            this.getSitesList();
            this._getJsonData();
            setTimeout(() => {
                this.loading = false;
            }, 500);
        }
    };
</script>

<style>

</style>